<?php

session_start();

if ($_SESSION['contactId']=='' AND ($_GET['query']!="login")) 
{
	echo "<Login/>";
	exit();
}

header('Pragma: no-cache');
header('Cache-Control: no-cache');
header('Content-Type: application/xml');
header('Content-Disposition: application/xml');

//set_error_handler("errorHandler");

$mysqli = new mysqli("localhost", "root", "", "ravebiz", "3306");

if ($mysqli)
{
	if ($_GET['query']=="login")
	{
		$query = "call login('".$_GET['u']."','".$_GET['p']."');";
		$result = $mysqli->query($query);

		if ($result)
		{
		    $row = $result->fetch_assoc();
			$contact_id = $row['contacts_id'];
			if ($contact_id!='') 
			{
				$pass = '1';
				$_SESSION['contactId'] = $contact_id;
			}
			$result->close();
		} 
		else echo "Login Failed.";
		
		$mysqli->close();

		//echo $pass."\n";
		exit();
	}

	if ($_REQUEST['q0'])
	{
		$i=0;
		while ($_REQUEST['q'.$i]!='')
		{
			$query=$_POST['q'.$i];
			$old  = array("`");
			$new = "'";
			$query = str_replace($old, $new, $query);


			//echo $query;
			$result = $mysqli->query($query);
			$i+=1;
		}
		exit();
	}	

	$result = $mysqli->query($_GET['query']);

	echo "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
	echo "<Response>\n";
	
	if ($result)
	{
		$count = $result->num_rows;

		echo "<Query>".$_GET['query']."</Query>\n";
		echo "<Data rowCount=\"".$count."\">\n";

		for ($i=0; $i<$count; $i++)
		{
		   $row = $result->fetch_assoc();
		   echo "     <r ";
		       foreach($row as $key => $value) {
		           print "$key='$value'\n        ";
		       }
		   echo " />\n";
		}

		$result->close();
		echo "</Data>\n";
	}
	$mysqli->close();

	echo "</Response>\n";
}
else echo "Could not connect to MySQL Server.";

function errorHandler($errno, $errstr, $errfile, $errline)
{
    printf("<Error>Connect failed: %s.</Error>\n", mysqli_connect_error());
}

?>
